package com.suncaper.wcss.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.suncaper.wcss.common.BaseConstant;
import com.suncaper.wcss.model.domain.AuditHistory;
import com.suncaper.wcss.mapper.AuditHistoryMapper;
import com.suncaper.wcss.model.domain.RoleFlowSetting;
import com.suncaper.wcss.service.AuditHistoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.suncaper.wcss.service.RoleFlowSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 审核历史表 服务实现类
 * </p>
 *
 * @author lxp
 * @since 2021-11-17
 */
@Service
public class AuditHistoryServiceImpl extends ServiceImpl<AuditHistoryMapper, AuditHistory> implements AuditHistoryService {

    @Autowired
    private RoleFlowSettingService roleFlowSettingService;

    @Override
    public List<AuditHistory> pageList(Long appId) {
        QueryWrapper<AuditHistory> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(AuditHistory::getApplicationId, appId).orderByAsc(AuditHistory::getGmtCreated);
        List<AuditHistory> list = baseMapper.selectList(wrapper);
        //这个list一定是整个流程

        //获取当前申请最近的审核节点
        if (list.size() == 0) {
            //还没有开始，需要拼装整个流程，起始节点为辅导员
            RoleFlowSetting curNode = roleFlowSettingService.getCurNodeByCode(BaseConstant.NODE_TEACHER);
            while (curNode.getNextNode() != 0) {
                AuditHistory auditHistory = new AuditHistory()
                        .setApplicationId(appId)
                        .setAuditNodeCode(curNode.getNodeCode())
                        .setAuditNodeName(curNode.getNodeName());
                list.add(auditHistory);
                curNode = roleFlowSettingService.getNextNodeByCode(curNode.getNodeCode());
            }

        }else{
            AuditHistory auditHistory = list.get(list.size() - 1);
            //获取最近的已经审核过的节点
            RoleFlowSetting curNode = roleFlowSettingService.getCurNodeByCode(auditHistory.getAuditNodeCode());
            while (curNode.getNextNode() != 0) {
               //需要添加进流程的是最近节点的下一个节点
                curNode = roleFlowSettingService.getNextNodeByCode(curNode.getNodeCode());
                //判断是否为结束节点
                if(curNode.getNextNode() != 0){
                    AuditHistory newAudit = new AuditHistory()
                            .setApplicationId(appId)
                            .setAuditNodeCode(curNode.getNodeCode())
                            .setAuditNodeName(curNode.getNodeName());
                    list.add(newAudit);
                }
            }
        }
        return list;
    }
}
